/**
 * @description user controller
 *
 * **/


const { getUserInfo, createUser, deleteUser } = require('../service/user')
const { SuccessResModel ,ErrorResModel } = require('../model/ResModel')
const { getUserInfoNotExist, getUserInfoExist, loginFailInfo } = require('../model/ErrorInfoModel')
const { enCrypto } = require('../utils/cryp')

async function isExist(userName) {
  // 进行业务逻辑处理
  // 查询数据 交给service 层处理
  const userInfo = await getUserInfo(userName)
  if (userInfo) {
    // 存在
    return new SuccessResModel(userInfo)
  } else {
    // 不存在
    return new ErrorResModel(getUserInfoNotExist)
  }
}

/**
 *
 * @method 用户注册
 * @param {string} userName
 * @param {string} password
 * @param {number} gender
 */
async function registerUser({ userName, password, gender}) {
  const userInfo = await getUserInfo(userName)
  if(userInfo) {
    return new ErrorResModel(getUserInfoExist)
  }
  try {
    const insertUser = await createUser({ userName, password, gender })
    return new SuccessResModel()
  } catch (error) {
    console.error(error.message,error.stack)
    return new ErrorResModel(registerFailInfo)
  }
}

/**
 *
 *
 * @param {object} ctx 请求上下文
 * @param {string} userName 用户名
 * @param {string} password 密码
 */
async function login(ctx, userName, password) {
  const userInfo = await getUserInfo(userName, enCrypto(password))
  // 登录失败
  if(!userInfo) {
    return new ErrorResModel(loginFailInfo)
  }

  // 登录成功
  if(ctx.session.userInfo == null) {
    ctx.session.userInfo = userInfo
  }
  return new SuccessResModel(userInfo)


}

async function deleteCurUser(userName) {
  const result = await deleteUser(userName)
  if(result) {
    return new SuccessResModel()
  }
  return new ErrorResModel(deleteUserFailInfo)
}

module.exports = {
  isExist,
  registerUser,
  login,
  deleteCurUser
}